//
//  UserAccount.swift
//  WBDemo
//
//  Created by Meng on 17/2/8.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    
    static let filePath: String = "userAccount.plist".docDir()
    static var user_account: UserAccount?
    
    var access_token: String?
    var expires_in: Int = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: TimeInterval(expires_in))
        }
    }
    var expires_date: NSDate?
    var uid: String?
    ///  用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 用户昵称
    var screen_name: String?
    
    init(dict: [String: AnyObject]) {
        // 如果要想初始化方法中使用KVC必须先调用super.init初始化对象
        // 如果属性是基本数据类型, 那么建议不要使用可选类型, 因为基本数据类型的可选类型在super.init()方法中不会分配存储空间
        super.init()
        self.setValuesForKeys(dict)
    }
    // 当KVC发现没有对应的key时就会调用
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    override var description: String {
        // 将模型转换为字典
        let property = ["access_token", "expires_in", "expires_date", "uid"]
        let dict = dictionaryWithValues(forKeys: property)
        // 将字典转换为字符串
        return "\(dict)"
    }
    // MARK: - NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        self.expires_in = aDecoder.decodeInteger(forKey: "expires_in")
        self.expires_date = aDecoder.decodeObject(forKey: "expires_date") as? NSDate
        self.uid = aDecoder.decodeObject(forKey: "uid") as? String
        self.screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        self.avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    // MARK: - 外部控制方法
    func saveUserAccount() -> Bool {
        return NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
    }
    class func readUserAccount() -> UserAccount? {
        if UserAccount.user_account != nil {
            return UserAccount.user_account
        }
        guard let account = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccount.filePath) as? UserAccount else {
            return nil
        }
        guard let date = account.expires_date, date.compare(Date()) != ComparisonResult.orderedAscending else {
            MYLog("过期了")
            return nil
        }
        
        UserAccount.user_account = account
        return account
    }
    class func isLogin() -> Bool {
        return (UserAccount.readUserAccount() != nil)
    }
    
    func loadUserInfo() {
        assert(access_token != nil, "使用该方法必须进行授权")
        let path = "2/users/show.json"
        let params = ["access_token":access_token!, "uid":uid!]
        NetworkTool.shareInstance.get(path, parameters: params, progress: nil, success: { (task, objc) in
            MYLog(objc)
            let dict = objc as! [String: AnyObject]
            self.screen_name = dict["screen_name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            MYLog(self.saveUserAccount())
        }) { (task, error) in
            MYLog(error)
        }
        
    }
}
